import { Form, Input, DatePicker, Radio, Select, Space, Button, InputNumber, Row, Col, Cascader } from "antd";
import React from "react";
import { getDateTime2 } from '@/utils/getDate'
import { apiGetCouponInfoAdd, apiGetCouponInfoEdit } from '@/request/coupons'
import { apiGetGoodsClassifyTreeAll } from '@/request/mallManagement'
import FormItem from "antd/lib/form/FormItem";
import { call } from "file-loader";
import '../style/style.less'
const { RangePicker } = DatePicker;

class Editor extends React.Component {
  state = {
    usePrice: -1,
    couponStock: -1,
    way: 1,
    usePriceInput: "",
    activityCountInput: "",
    loading: false,
    couponType: 'J',
    timeType: 0,
    cdKeyState: 1,
    passwordState: 1,
    exchangeType: '1',
    cdkNumState: true,
    required: false,
    requiredCommand: false,
    quotaNum: undefined,
    classifyTree: [],
    intervalDay: undefined,
    options: [
      {
        label: '7天',
        value: 7
      },
      {
        label: '15天',
        value: 15
      },
      {
        label: '30天',
        value: 30
      },
      {
        label: '60天',
        value: 60
      },
    ],
    classifyCheckStatusDis: false
  };
  componentDidMount() {
    if (this.props.type === 'editor') {
      const { usePrice, couponStock, startTime, endTime, couponPrice, couponType, timeType, effectiveTime, cdKeyState } = this.props.editorValue
      let value = { ...this.props.editorValue }
      if (parseInt(usePrice) !== -1) {
        value.usePrice = 2
        this.setState({ usePriceInput: React.$transNum(usePrice, 2, -2), usePrice: 2, useKey: new Date().getTime() })
      } else {
        value.usePrice = parseInt(usePrice)
      }
      if (parseInt(couponStock) !== -1) {
        value.couponStock = 2
        this.setState({ activityCountInput: couponStock, couponStock: 2, activeKey: new Date().getTime() + 1 })
      } else {
        value.couponStock = parseInt(couponStock)
      }
      value.time = [React.$moment(`${startTime}`), React.$moment(`${endTime}`)]
      value.couponPrice = couponType === 'Z' ? React.$transNum(couponPrice, 1, -1) : React.$transNum(couponPrice, 2, -2)
      this.setState({
        couponType
      })
      this.formRef.setFieldsValue({ ...value })
    }
    this.getGoodsClassifyTreeAll()
  };
  getGoodsClassifyTreeAll = async () => {
    const res = await apiGetGoodsClassifyTreeAll()
    if (res.code === 0) {
      this.setState({
        classifyTree: res.data.map((v) => {
          return {
            value: v.value,
            label: v.label,
            children: v.children.length > 0 ? v.children : []
          }
        }),
      })
    }
  }

  usePriceChange = (e) => {
    this.setState({ usePrice: e.target.value });
    if (e.target.value === 1) {
      this.usePrice.state.value = "";
    }
  };
  activityCountChange = (e) => {
    this.setState({ couponStock: e.target.value });
    if (e.target.value === 1) {
      this.couponStock.state.value = "";
    }
  };
  wayChange = (e) => {
    this.setState({ way: e.target.value });
  };
  usePriceInputChange = (e) => {
    this.setState({ usePriceInput: e });
  };
  activityCountInputChange = (e) => {
    this.setState({ activityCountInput: e });
  };
  onFinish = async (value) => {
    console.log(value, 'value');
    const { usePrice, couponStock, passwordState, usePriceInput, activityCountInput, couponType, timeType, cdKeyState } = this.state
    if (cdKeyState !== 1 && couponStock !== -1 && passwordState == 1) {
      if (value.cdKeyNum > activityCountInput) {
        this.setState({ loading: false })
        return React.$message({
          type: 'warning',
          content: `CDK数量不可超过优惠券数量`
        })
      }
    }
    if (passwordState != 1 && couponStock !== -1 && cdKeyState == 1 && value.passwordNum) {
      if ((value.passwordNum) > activityCountInput) {
        this.setState({ loading: false })
        return React.$message({
          type: 'warning',
          content: `口令券数量不可超过领取张数`
        })
      }
    }
    if (passwordState != 1 && couponStock !== -1 && cdKeyState !== 1 && value.passwordNum) {
      if ((value.passwordNum + value.cdKeyNum) > activityCountInput) {
        this.setState({ loading: false })
        return React.$message({
          type: 'warning',
          content: `口令券与CDK数量数量总和不可超过领取张数`
        })
      }
    }
    if (usePrice !== -1) {
      value.usePrice = React.$transNum(usePriceInput, 0, 2)
    }
    if (couponStock !== -1) {
      value.couponStock = activityCountInput
    }
    if (timeType === 0) {
      value.startTime = getDateTime2(value.time[0])
      value.endTime = getDateTime2(value.time[1])
      delete (value.time)
    }
    value.couponPrice = couponType === 'Z' ? React.$transNum(value.couponPrice, 0, 1) : React.$transNum(value.couponPrice, 0, 2)
    if (couponType === 'Z') {
      value.couponMaxPrice = value.couponMaxPrice === undefined ? -1 : value.couponMaxPrice * 100
    }
    // 手动触发表单校验 每人限领字段 

    if (value.exchangeType == 0) {
      this.formRef.validateFields(['exchangeCount']);
      this.formRef.validateFields(['exchangeDays']);
      value.exchangeCount = value.exchangeCount === null || value.exchangeCount === undefined ? -1 : value.exchangeCount
      value.exchangeDays = value.exchangeDays === null || value.exchangeDays === undefined ? -1 : value.exchangeDays
    } else {
      value.exchangeCount = value.exchangeCount === null || value.exchangeCount === undefined ? -1 : value.exchangeCount
    }
    value.passwordNum = value.passwordNum === null || value.passwordNum === undefined ? -1 : value.passwordNum
    if (cdKeyState == 1) {
      delete value.cdKeyNum
    }
    if (passwordState == 1) {
      delete value.passwordNum
      delete value.password
    }
    if (value.classifyCheckStatus === '0' || value.classifyCheckStatus === '2') {
      delete value.classifyList
    } else {
      value.classifyList = value.classifyList.map(item => {
        return item[item.length - 1]
      })
    }
    console.log(value, 'asd');
    // this.setState({ loading: true })
    if (this.props.type === 'editor') {
      let response = await apiGetCouponInfoEdit({ ...value, couponId: this.props.couponId })
      if (response.code === 0) {
        this.props.handleCancel()
        this.props.reload()
      }
    } else {
      let res = await apiGetCouponInfoAdd({ ...value })
      if (res.code === 0) {
        this.props.handleCancel()
        this.props.reload()
      }
    }

  }
  classifyChange = e => {
    if (e.target.value === 'Z') {
      this.classifyCheckStatusDis = true;
      this.formRef.setFieldsValue({ "classifyCheckStatus": "0" })
    }
    else {
      this.classifyCheckStatusDis = false;
    }
    this.setState({
      couponType: e.target.value
    })
  }
  timeTypeChange = (e) => {
    this.setState({
      timeType: e.target.value
    })
  }
  cdKeyStateChange = (e) => {
    if (e.target.value == 0) {
      this.setState({
        cdkNumState: false,
        cdKeyState: e.target.value,
        required: true,

      })

    } else {
      this.setState({
        cdkNumState: true,
        cdKeyState: e.target.value,
        required: false,
      })
    }
  }
  commandChange(e) {
    this.formRef.validateFields(['exchangeCount']);
    console.log(1);
    this.setState({
      requiredCommand: e.target.value === 0,
      passwordState: e.target.value
    })

  }
  checkDays(rules, value, callback) {
    const values = this.formRef.getFieldsValue()
    const { exchangeCount, exchangeDays } = values
    console.log(values, 'values', exchangeCount, exchangeDays);
    if (exchangeCount > 0 && !exchangeDays) {
      callback('请添写天数')
    } else {
      callback()
    }

  }
  checkCount(rules, value, callback) {

    const values = this.formRef.getFieldsValue()
    const { exchangeCount, exchangeDays } = values

    console.log(exchangeCount, exchangeDays, this.formRef);

    if (exchangeDays > 0 && !exchangeCount) {
      callback('请添写张数')
    } else {
      callback()
    }

  }
  exchangeDaysChange(e) {
    console.log(e, this.formRef);
    this.formRef.setFieldsValue({
      exchangeDays: e
    })
  }
  exchangeCountChange(e) {
    console.log(e, this.formRef);
    this.formRef.setFieldsValue({
      exchangeCount: e
    })
  }

  exchangeTypeChange(e) {
    this.formRef.setFieldsValue({
      exchangeCount: undefined,
      exchangeDays: undefined
    })
  }
  render() {
    const { usePrice, intervalDay, quotaNum, usePriceInput, couponStock, passwordState, classifyTree, requiredCommand, exchangeType, activityCountInput, loading, useKey, activeKey, couponType, timeType, cdKeyState, cdkNumState, options, required } = this.state;
    return (
      <div>
        <Form initialValues={{ couponType, classifyCheckStatus: '0', couponStock, passwordState, usePrice, timeType, cdKeyState, exchangeType }} ref={ref => this.formRef = ref} onFinish={this.onFinish}>
          <Row gutter={12}>
            <Col span={12}>
              <Form.Item label="优惠券标题" name="couponTitle" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="优惠券类型" name="couponType" rules={[{ required: true }]}>
                <Radio.Group onChange={this.classifyChange} defaultValue={couponType}>
                  <Radio value={'J'}>代金券</Radio>
                  <Radio value={'Z'}>折扣券</Radio>
                  <Radio value={'D'}>打车券</Radio>
                </Radio.Group>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="限制品类" name="classifyCheckStatus">
                <Radio.Group >
                  <Radio value={'0'}>不限制品类使用</Radio>
                  <Radio disabled={this.classifyCheckStatusDis} value={'1'}>限制品类使用</Radio>
                  <Radio value={'2'}>限制服务类使用</Radio>
                </Radio.Group>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item style={{ marginBottom: 0 }} shouldUpdate={(prevValues, currentValues) => prevValues.classifyCheckStatus !== currentValues.classifyCheckStatus}>
                {({ getFieldValue }) => {
                  return (
                    <Form.Item label="使用类目" name="classifyList" style={{ marginBottom: 0 }} rules={[
                      { required: getFieldValue('classifyCheckStatus') === '1' }
                    ]}>
                      <Cascader disabled={getFieldValue('classifyCheckStatus') === '0' || getFieldValue('classifyCheckStatus') === '2'} options={classifyTree} width={200} multiple changeOnSelect placeholder="请选择商品类目" />
                    </Form.Item >
                  )
                }
              }
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label={`优惠券${couponType === 'Z' ? '折扣' : '面值'}`} name="couponPrice" rules={[{ required: true }]}>
                <InputNumber
                  precision={couponType === 'Z' ? 1 : 2}
                  max={couponType === 'Z' ? 9.9 : Infinity}
                  min={couponType === 'Z' ? 0.1 : 0.01} />
              </Form.Item>
            </Col>
            {
              couponType === 'Z' ?
                <Col span={12}>
                  <Form.Item label={`优惠券最大折扣金额`} name="couponMaxPrice" >
                    <InputNumber />
                  </Form.Item>
                </Col> : null
            }
            <Col span={12}>
              <Form.Item label="CDK关联" name="cdKeyState" rules={[{ required: true }]}>
                <Radio.Group onChange={(e) => this.cdKeyStateChange(e)} defaultValue={cdKeyState}>
                  <Radio value={0}>启用</Radio>
                  <Radio value={1}>不启用</Radio>
                </Radio.Group>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="CDK数量" name="cdKeyNum" rules={[{ required: required }]}>
                <InputNumber disabled={cdkNumState} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="口令关联" name="passwordState" rules={[{ required: true }]}>
                <Radio.Group onChange={(e) => this.commandChange(e)} defaultValue={passwordState}>
                  <Radio value={0}>启用</Radio>
                  <Radio value={1}>不启用</Radio>
                </Radio.Group>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="口令" name="password" rules={[{ required: requiredCommand }]}>
                <Input disabled={passwordState === 1} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="口令券数量" name="passwordNum" >
                <InputNumber disabled={passwordState === 1} min={0} precision={0} step placeholder="不限制" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="期限类型" name="timeType" rules={[{ required: true }]}>
                <Radio.Group onChange={this.timeTypeChange} defaultValue={timeType}>
                  <Radio value={0}>活动周期</Radio>
                  <Radio value={1}>领取之日起</Radio>
                </Radio.Group>
              </Form.Item>
            </Col>
            {timeType == 0 ? <Col span={12}>
              <Form.Item label="活动周期" name="time" rules={[{ required: true }]}>
                <RangePicker showTime />
              </Form.Item>
            </Col> : <Col span={12}>
              <Form.Item label="领取之日起" name="effectiveTime" rules={[{ required: true }]}>
                <Select options={options} placeholder={"请选择优惠券有效期"} />
              </Form.Item>
            </Col>}

            <Col span={12}>
              <Form.Item label="使用门槛" name="usePrice" rules={[{ required: true }]}>
                <Radio.Group onChange={this.usePriceChange} defaultValue={usePrice}>
                  <Radio value={-1}>无门槛</Radio>
                  <Radio value={2}>
                    <div style={{ display: "flex", alignItems: "center" }}>
                      满
                      <InputNumber
                        precision={2}
                        min={0.01}
                        key={useKey}
                        defaultValue={usePriceInput}
                        ref={(ref) => (this.usePrice = ref)}
                        onChange={this.usePriceInputChange}
                        disabled={usePrice === -1}
                        style={{ width: 100, margin: "0 10px" }}
                      />
                      可用
                    </div>
                  </Radio>
                </Radio.Group>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="领取张数" name="couponStock" rules={[{ required: true }]}>
                <Radio.Group onChange={this.activityCountChange} defaultValue={couponStock}>
                  <Radio value={-1}>不限</Radio>
                  <Radio value={2}>
                    <div style={{ display: "flex", alignItems: "center" }}>
                      共
                      <InputNumber
                        precision={0}
                        min={0}
                        key={activeKey}
                        defaultValue={activityCountInput}
                        ref={(ref) => (this.couponStock = ref)}
                        onChange={this.activityCountInputChange}
                        disabled={couponStock === -1}
                        style={{ width: 100, margin: "0 10px" }}
                      />
                      张
                    </div>
                  </Radio>
                </Radio.Group>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="是否开启按天限领" name="exchangeType" rules={[{ required: true }]}>
                <Radio.Group defaultValue={'1'} onChange={(e) => this.exchangeTypeChange(e)}>
                  <Radio value={'0'}>启用</Radio>
                  <Radio value={'1'}>不启用</Radio>
                </Radio.Group>
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item shouldUpdate={(prevValues, currentValues) => prevValues.exchangeType !== currentValues.exchangeType}>
                {({ getFieldValue }) => {
                  return (
                    getFieldValue('exchangeType') === '0' ? (
                      <Row>
                        <Form.Item name='exchangeDays' label="每人限领" rules={[
                          {
                            validator: this.checkDays.bind(this)
                          }
                        ]}>

                          每人&nbsp;&nbsp;<InputNumber min={1} precision={0} onChange={(e) => this.exchangeDaysChange(e)} style={{ width: 100 }} placeholder="不限制"></InputNumber>&nbsp;&nbsp;日，限领


                        </Form.Item >
                        <Form.Item name={'exchangeCount'} rules={[
                          {
                            validator: this.checkCount.bind(this)
                          }
                        ]}>
                          &nbsp;&nbsp;<InputNumber min={1} precision={0} onChange={(e) => this.exchangeCountChange(e)} style={{ width: 100 }} placeholder="不限制"></InputNumber>&nbsp;&nbsp;张
                        </Form.Item>
                      </Row>
                    ) :
                      <Form.Item name={'exchangeCount'} rules={[
                        {
                          validator: this.checkCount.bind(this)
                        }
                      ]} label="每人限领" ><InputNumber min={1} precision={0} placeholder="不限制"></InputNumber>
                      </Form.Item>
                  )
                }
                }


              </Form.Item>
            </Col>















            {/* <Form.Item label="每人限领" name="everyoneQuota" rules={[{ required: true }]}>
            <InputNumber placeholder="不限制"></InputNumber>
          </Form.Item> */}

            {/* <Form.Item label="获取方式" name="activityWay" rules={[{ required: true }]}>
            <Select options={[{ label: '注册获取', value: 'REGISTERED' }]} />
          </Form.Item> */}



            {/* <Form.Item label="发放方式">
            <Radio.Group onChange={this.wayChange} value={way}>
              <Radio value={1}>全部用户</Radio>
              <Radio value={2}>指定用户</Radio>
            </Radio.Group>
            <div
              style={{
                marginTop: 15,
                visibility: way === 1 ? "hidden" : "unset",
              }}
            >
              <Select />
            </div>
          </Form.Item> */}
            <Col span={12}>
              <Form.Item>
                <div style={{ display: "flex", justifyContent: "flex-end", marginBottom: -30 }}>
                  <Space>
                    <Button onClick={this.props.handleCancel}>取消</Button>
                    <Button loading={loading} htmlType="submit" type="primary">保存</Button>
                  </Space>
                </div>
              </Form.Item>
            </Col>
          </Row>

        </Form>
      </div >
    );
  }
}

export default Editor;